package com.lancoo.znbkxx.teacher.diagnosis

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.View
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseActivity
import com.lancoo.znbkxx.teacher.model.data.Time
import com.lancoo.znbkxx.teacher.net.BkApiMethods
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import kotlinx.android.synthetic.main.activity_vocab_trail.*
import kotlinx.android.synthetic.main.item_achievement_markview.view.*
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeoutException

/**
 *@author Admin
 *@date 2020/12/25
 *
 */
class VocabTrailActivity : BaseActivity(), View.OnClickListener {
    private val totalVocab = mutableListOf<Entry>()
    private val listenVocab = mutableListOf<Entry>()
    private val writeVocab = mutableListOf<Entry>()
    private val xLabels = mutableListOf<String>()
    private val zsd by lazy { intent.getStringExtra("zsd") }
    private val stuID by lazy { intent.getStringExtra("stuID") }
    private lateinit var lineChartData: LineData
    private lateinit var dataSetListen: LineDataSet
    private lateinit var dataSetWrite: LineDataSet
    override fun setLayout(): Int {
        return R.layout.activity_vocab_trail
    }

    override fun initView() {
        iv_back.setOnClickListener(this)
        textView51.setOnClickListener(this)
        textView52.setOnClickListener(this)
        getStuVocabRZPlate()
    }

    override fun isNeedToolBar(): Boolean {
        return false
    }

    @SuppressLint("CheckResult")
    fun getStuVocabRZPlate() {
        val method = BkApiMethods(this)
        val params = BkApiMethods.Paramas()
        params["ZsdArea"] = zsd
        params["StuID"] = stuID
        method.getStuVocabRZPlate(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                initLineChart(it.Data.TimeList)
            } else {
                MyToast.showToast( it.Message)
            }
        }, {
            val error: String = if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                getString(R.string.aibk_network_timeout)
            } else {
                getString(R.string.aibk_server_sick)
            }
            MyToast.showToast(error)
        })
    }

    private fun initLineChart(timeList: List<Time>) {
        if (timeList.isEmpty()) {
            group.visibility = View.INVISIBLE
            tv_empty.visibility = View.VISIBLE
            return
        }
        totalVocab.clear()
        listenVocab.clear()
        writeVocab.clear()
        xLabels.clear()
        timeList.forEachIndexed { index, time ->
            val entryTotal = Entry(index.toFloat(), time.TotalPersonalWord.toFloat())
            val entryListen = Entry(index.toFloat(), time.LSPersonalWord.toFloat())
            val entryWrite = Entry(index.toFloat(), time.RWPersonalWord.toFloat())
            totalVocab.add(entryTotal)
            listenVocab.add(entryListen)
            writeVocab.add(entryWrite)
            xLabels.add(time.DayTime)
        }
        lineChart.apply {
            val dataSetTotal = LineDataSet(totalVocab, "total").apply {
                isHighlightPerTapEnabled = false
                color = Color.parseColor("#22d7bb")
                setCircleColor(Color.parseColor("#22d7bb"))
                lineWidth = 2f
                circleRadius = 2.5f
                setDrawCircleHole(true)
                circleHoleRadius = 1.5f
            }
            dataSetListen = LineDataSet(listenVocab, "listen").apply {
                isHighlightEnabled = false
                color = Color.parseColor("#2dbcff")
                setCircleColor(Color.parseColor("#2dbcff"))
                lineWidth = 2f
                circleRadius = 2.5f
                setDrawCircleHole(true)
                circleHoleRadius = 1.5f
            }
            dataSetWrite = LineDataSet(writeVocab, "write").apply {
                isHighlightEnabled = false
                color = Color.parseColor("#ffd234")
                setCircleColor(Color.parseColor("#ffd234"))
                lineWidth = 2f
                circleRadius = 2.5f
                setDrawCircleHole(true)
                circleHoleRadius = 1.5f
            }
            lineChartData = LineData(dataSetTotal)
            lineChartData.setDrawValues(false)
            data = lineChartData
            axisLeft.apply {
                textColor = Color.parseColor("#999999")
                spaceBottom = 0f
                axisMinimum = 0f
            }
            axisRight.isEnabled = false
            legend.isEnabled = false
            description.isEnabled = false
            setPinchZoom(false)
            setScaleEnabled(false)
            val markerView = MyMarkView(this@VocabTrailActivity, R.layout.item_achievement_markview)
            markerView.chartView = this
            marker = markerView
            xAxis.apply {
                axisMinimum = -0.5f
                axisMaximum = timeList.size.toFloat() + 0.5f
                position = XAxis.XAxisPosition.BOTTOM
                isGranularityEnabled = true
                labelCount = xLabels.size
                setDrawGridLines(false)
                textSize = 11f
                textColor = Color.parseColor("#999999")
                valueFormatter = IndexAxisValueFormatter(xLabels)
            }
            animateX(1000)
        }
    }

    inner class MyMarkView(context: Context, layoutResource: Int) :
            MarkerView(context, layoutResource) {
        @SuppressLint("SetTextI18n")
        override fun refreshContent(e: Entry?, highlight: Highlight?) {
            val position = e!!.x.toInt()
            tv_hint.text = "总词汇量：${totalVocab[position].y.toInt()}" +
                    (if (textView51.tag == 1) "\n听说词汇量：${listenVocab[position].y.toInt()}" else "") +
                    if (textView52.tag == 1) "\n阅读词汇量：${writeVocab[position].y.toInt()}" else ""
            super.refreshContent(e, highlight)
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back -> finish()
            R.id.textView51 -> {
                if (textView51.tag == "0") {
                    textView51.tag = 1
                    textView51.alpha = 1f
                    lineChartData.addDataSet(dataSetListen)
                } else {
                    textView51.tag = "0"
                    textView51.alpha = 0.5f
                    lineChartData.removeDataSet(dataSetListen)
                }
                lineChartData.setDrawValues(false)
                lineChart.notifyDataSetChanged()
                lineChart.invalidate()
            }
            R.id.textView52 -> {
                if (textView52.tag == "0") {
                    textView52.tag = 1
                    textView52.alpha = 1f
                    lineChartData.addDataSet(dataSetWrite)
                } else {
                    textView52.tag = "0"
                    textView52.alpha = 0.5f
                    lineChartData.removeDataSet(dataSetWrite)
                }
                lineChartData.setDrawValues(false)
                lineChart.notifyDataSetChanged()
                lineChart.invalidate()
            }
        }
    }
}